package hz.mobileproject.pda.ui.frgment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import hz.mobileproject.pda.R;
import hz.mobileproject.pda.entity.MessageEvent;
import hz.mobileproject.pda.entity.request.Request_BeingProcess;
import hz.mobileproject.pda.entity.request.Request_OverProcess;
import hz.mobileproject.pda.entity.request.Request_data;
import hz.mobileproject.pda.entity.response.Response_BedingProcess;
import hz.mobileproject.pda.network.Constance;
import hz.mobileproject.pda.ui.adapter.BeingProcessAdapter;
import hz.mobileproject.pda.ui.view.ContentSummaryOtherDialog;
import hz.mobileproject.pda.utils.Base64;

/**
 * Created by zmybi on 2017/10/23.
 */

public class BeingProcessFragment extends Fragment implements AdapterView.OnItemClickListener {

    private ListView lv_being_process;
    private Gson gson;
    private SPUtils mSpUtils;

    private List<Response_BedingProcess> mResponse_bedingProcessList;
    private BeingProcessAdapter npAdapter;
    //点击结束的条目
    private Response_BedingProcess bp;

    public static BeingProcessFragment getInstance() {
        return new BeingProcessFragment();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        EventBus.getDefault().register(this);

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fr_being_process, null);
        lv_being_process = (ListView) view.findViewById(R.id.lv_being_process);
        lv_being_process.setOnItemClickListener(this);
        gson = new Gson();
        mSpUtils = SPUtils.getInstance("app_login");
        npAdapter = new BeingProcessAdapter(getActivity(),new ArrayList<Response_BedingProcess>());
        lv_being_process.setAdapter(npAdapter);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

    @Override
    public void onResume() {
        super.onResume();

        getListFromNet();

    }

    private void getListFromNet() {
        String cus_number = mSpUtils.getString("cusnumber","");
        String dept_id = mSpUtils.getString("department_id","");
        Request_BeingProcess request_beingProcess = new Request_BeingProcess(cus_number,dept_id);
        //请求接口
        String gnpStr = gson.toJson(request_beingProcess);
        LogUtils.e(gnpStr);
        Request_data data = new Request_data();
        data.setData(Base64.getBase64(gnpStr));
        String body_data = gson.toJson(data);

        RequestParams params = new RequestParams(Constance.BASE_URL + "/"+ Constance.PROJECT_NAME+ "/grid/processingList");
        params.setBodyContent(body_data);
        x.http().post(params, callback);
    }

    /**
     * 获取列表数据回调
     */
    private Callback.CommonCallback<String> callback = new Callback.CommonCallback<String>() {
        @Override
        public void onSuccess(String result) {
            try {
                LogUtils.e("处理中请求网络了");
                JsonObject returnData = new JsonParser().parse(result).getAsJsonObject();
                String returnStr = Base64.getFromBase64(returnData.get("data").getAsString());
                LogUtils.e(returnStr);
                ArrayList<Response_BedingProcess> listData = gson.fromJson(returnStr,
                        new TypeToken<ArrayList<Response_BedingProcess>>() {}.getType());
                if(listData == null){
                    listData = new ArrayList<>();
                }
                for(int i = 0; i < listData.size();i++) {
                    //设置倒计时长
                    String my_start_time = listData.get(i).start_time;
                    String my_interval_time = listData.get(i).interval_time;
                    Long start_time_lg = TimeUtils.string2Millis(my_start_time);
                    Long endTime = Integer.parseInt(my_interval_time) * 60 * 1000 + start_time_lg;
                    listData.get(i).setExpirationTime(endTime);

//                    String server_time = listData.get(i).server_time;
//                    String start_time = listData.get(i).start_time;
//                    Long timeSeconds = TimeUtils.getTimeSpan(server_time,start_time, TimeConstants.MSEC);
//                    String interval_time = listData.get(i).interval_time;
//                    //剩余时间
//                    Long leftTime = Integer.parseInt(interval_time) * 60 * 1000  -timeSeconds ;
//                    listData.get(i).setExpirationTime(System.currentTimeMillis() + leftTime);
                }
                npAdapter.setListData(listData);

                if(listData.size()==0){
                    Toast.makeText(getActivity(),"没有更多数据了",Toast.LENGTH_LONG).show();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            LogUtils.e(ex.toString());
            Toast.makeText(getActivity(),"获取数据失败",Toast.LENGTH_LONG).show();
        }

        @Override
        public void onCancelled(CancelledException cex) {

        }

        @Override
        public void onFinished() {

        }
    };

    @Override
    public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
        bp = (Response_BedingProcess)npAdapter.getItem(position);
        Response_BedingProcess clickBeingProcessBean = npAdapter.getListData().get(position);
        ContentSummaryOtherDialog dialog = new ContentSummaryOtherDialog(getContext());
        final Request_OverProcess myOp = new Request_OverProcess();
        myOp.setCus_number(bp.cus_number);
        myOp.setId(bp.id);
        myOp.setTime( TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));
        myOp.setStart_time(bp.start_time);
        myOp.setDept_id(bp.dept_id);
        myOp.setDept_name(bp.dept_name);
        myOp.setPolice_id(bp.police_id);
        myOp.setPolice_name(bp.police_name);
        myOp.setEvent_id(bp.event_id);
        myOp.setInterval_time(bp.interval_time);
        myOp.setTerm_id(bp.term_id);
        myOp.setFactory_id(bp.factory_id);
        myOp.setFactory_name(bp.factory_name);
        if(clickBeingProcessBean.getIsChaoShi()) {
            myOp.setState("4");
        }else {
            myOp.setState("3");  //没有超时  正常
            myOp.setEx_remark("");
        }
        dialog.setTitle("是否完成此条事件").setMessage("输入超时原因")
                .setContentMaxLength(80)
                .setContentVisable(clickBeingProcessBean.getIsChaoShi())
                .setOnClickListener(new ContentSummaryOtherDialog.OnClickListener() {
                    @Override
                    public void onPositiveClick(String s) {
                        myOp.setEx_remark(s);
                        //请求接口
                        String opStr = gson.toJson(myOp);
                        LogUtils.e(opStr);
                        Request_data data = new Request_data();
                        data.setData(Base64.getBase64(opStr));
                        String body_data = gson.toJson(data);

                        RequestParams params = new RequestParams(Constance.BASE_URL + "/" +Constance.PROJECT_NAME+"/grid/over");
                        params.setBodyContent(body_data);
                        x.http().post(params, overCallback);
                    }
                    @Override
                    public void onNagetiveClick() {

                    }
                }).show();
    }

    /**
     * 完成事件
     */
    private Callback.CommonCallback<String> overCallback = new Callback.CommonCallback<String>() {
        @Override
        public void onSuccess(String result) {
            try {
                JsonObject returnData = new JsonParser().parse(result).getAsJsonObject();
                LogUtils.e(returnData.toString());
                int rtnCode = Integer.valueOf(returnData.get("rtnCode").getAsString());
                if(rtnCode == 0){
                    ToastUtils.showLong("操作成功");
                    npAdapter.removeData(bp);
                }else{
                    ToastUtils.showLong("操作失败");
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            LogUtils.e(ex.toString());
            Toast.makeText(getActivity(),"事件完成提交失败",Toast.LENGTH_LONG).show();
        }

        @Override
        public void onCancelled(CancelledException cex) {

        }

        @Override
        public void onFinished() {

        }
    };




    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        npAdapter.cancelAllTimers();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event){
        //收到Activity的消息
        getListFromNet();
    }
}
